<template>
    <div>
        <global-tables
            :total="total"
            :list="list"
            :loading="loading"
            :columns="columns"
            :current="search.pageindex"
            @changePage="handleChangePage"
            @handleAllSelect="handleAllSelect"
        >
            <Form :model="search" :label-width="80">
                <div class="table-top-wrap">
                    <div>
                        <Button v-if="isAddBtn" class="features-btn" @click="handleBtnClick(null,'add')">
                            <Icon type="md-add" size="18"/>新建
                        </Button>
                    </div>
                    <!-- <div class="table-top-wrap-bottom">
                        <div>
                            <Select v-model="search.groupid" style="width:100px;margin:0 10px" placeholder="审批类别">
                                <Option :value="item.ID + ''" v-for="item in dataList" v-bind:key="item.id">{{item.GroupName}}</Option>
                            </Select>
                        </div>
                        <div>
                            <input type="text" class="style-input" @keyup.enter="handleSearch" v-model="search.keyword" placeholder="请输入发起人 / 审批人">
                            <i-input style="display:none"></i-input>
                        </div>
                        <div>
                            <Button icon="ios-search" class="search-btn" @click="handleSearch">搜索</Button>
                        </div>
                    </div>-->
                </div>
            </Form>
        </global-tables>
        <div>
            <!-- 新建 -->
            <Modal :mask-closable="false" v-model="isModal" :title="ModalTitle">
                <div v-if="isModal">
                    <Form ref="formItem" :model="formItem" :rules="ruleValidate" :label-width="100">
                        <Row>
                            <i-col :lg="{ span: 15}">
                                <FormItem label="专区名称" prop="SpecialArea">
                                    <Input v-model="formItem.SpecialArea" placeholder="请输入专区名称" style="width: 300px"/>
                                </FormItem>
                            </i-col>
                            <i-col :lg="{ span: 24}">
                                <FormItem label="板块选择" prop="currentPersonnel">
                                    <CheckboxGroup v-model="formItem.currentPersonnel" @on-change="getplateData()">
                                        <Checkbox v-for="item in personnelList" :key="item.ID" :label="item.ID + `/${item.ModelName}`">{{item.ModelName}}</Checkbox>
                                    </CheckboxGroup>
                                </FormItem>
                            </i-col>
                        </Row>
                        <Row>
                            <i-col :lg="{ span: 24}">
                                <FormItem label="顺序">
                                    <div v-for=" (item,index) in formItem.Order" :key="index">
                                        {{index+1}}、{{item}}
                                        <Icon type="md-arrow-round-down" style="font-size:20px;cursor:pointer" @click="Sort('DescendingOrder',index)"/>
                                        <Icon type="md-arrow-round-up" style="font-size:20px;cursor:pointer" @click="Sort('AscendingOrder',index)"/>
                                    </div>
                                </FormItem>
                            </i-col>
                        </Row>
                    </Form>
                </div>
                <div slot="footer">
                    <Button size="large" @click="handleClose('userClose')">取消</Button>
                    <Button type="primary" size="large" @click="handleSubmit()">确定</Button>
                </div>
            </Modal>
        </div>
    </div>
</template>

<script>
/**
 * 专区列表
 */
import { cyclicRouting } from '@/util';
import { getModulePermission } from '@/api/user';
import GlobalTables from '@/components/GlobalTables';
import Api from './service';
//import { setTimeout } from 'timers';
export default {
    name: 'OnlineArea',
    components: {
        GlobalTables
    },
    data() {
        return {
            isModal: false,
            loading: true,
            isApprover: false,
            total: 0,
            ModalTitle: '新建专区',
            isAddBtn: false,
            isEdit: false,
            allSelectArr: null,
            roleList: [],
            personnelList: [],
            dataList: [],
            itemId: null,
            formItem: this.initFormValidate(),
            ruleValidate: this.initRuleValidate(),
            search: {
                keyword: '',
                pageindex: 1,
                groupid: '',
                pagesize: 10,
                type: ''
            },
            columns: [
                {
                    type: 'selection',
                    width: 60,
                    align: 'center'
                },
                {
                    title: '专区名称',
                    key: 'PageName'
                },
                {
                    title: '内容',
                    key: 'ModelNames'
                },
                {
                    title: '操作',
                    width: 70,
                    align: 'center',
                    render: (h, params) => {
                        const { isEdit } = this;
                        return h('div', [
                            isEdit &&
                                h(
                                    'Button',
                                    {
                                        props: {
                                            type: 'primary',
                                            size: 'small'
                                        },
                                        style: {
                                            background: '#5ab1ef',
                                            border: 'none',
                                            marginRight: '5px'
                                        },
                                        on: {
                                            click: () => {
                                                this.handleBtnClick(params.row, 'edit');
                                            }
                                        }
                                    },
                                    '修改'
                                )
                        ]);
                    }
                }
            ],
            list: []
        };
    },
    mounted() {
        /* 获取菜单的id */
        cyclicRouting(JSON.parse(sessionStorage.getItem('user')).menuList, this.$route, id => {
            /* 按钮权限请求 */
            getModulePermission({
                roleid: JSON.parse(sessionStorage.getItem('user')).roleid,
                moduleid: id
            }).then(res => {
                /* 按钮权限赋值 */
                for (let item in res.data) {
                    if (res.data[item].name == 'add') {
                        /* 如果用户权限有新建 */
                        this.isAddBtn = true;
                    } else if (res.data[item].name == 'edit') {
                        this.isEdit = true;
                    }
                }
                /* 列表请求 */
                this.getTablesListData();
            });
        });
    },
    methods: {
        Sort(type, index) {
            if (type == 'DescendingOrder') {
                //降序
                if (index != this.formItem.Order.length - 1) {
                    this.formItem.Order[index] = this.formItem.Order.splice(index + 1, 1, this.formItem.Order[index])[0];
                    this.formItem.OrderID[index] = this.formItem.OrderID.splice(index + 1, 1, this.formItem.OrderID[index])[0];
                } else {
                    this.formItem.Order.unshift(this.formItem.Order.splice(index, 1)[0]);
                    this.formItem.OrderID.unshift(this.formItem.OrderID.splice(index, 1)[0]);
                }
            } else {
                //升序
                if (index != 0) {
                    this.formItem.Order[index] = this.formItem.Order.splice(index - 1, 1, this.formItem.Order[index])[0];
                    this.formItem.OrderID[index] = this.formItem.OrderID.splice(index - 1, 1, this.formItem.OrderID[index])[0];
                } else {
                    this.formItem.Order.push(this.formItem.Order.shift());
                    this.formItem.OrderID.push(this.formItem.OrderID.shift());
                }
            }
        },
        getplateData() {
            this.formItem.OrderID = [];
            this.formItem.Order = [];
            for (let item in this.formItem.currentPersonnel) {
                this.formItem.OrderID.push(
                    this.formItem.currentPersonnel[item].substring(0, this.formItem.currentPersonnel[item].indexOf('/'))
                );
                this.formItem.Order.push(
                    this.formItem.currentPersonnel[item].substring(
                        this.formItem.currentPersonnel[item].indexOf('/') + 1,
                        this.formItem.currentPersonnel[item].length
                    )
                );
            }
        },
        /* 表格数据请求 */
        getTablesListData() {
            const data = this.search;
            Api.getTablesList(data).then(res => {
                this.list = res.data.rows;
                this.loading = false;
                this.total = res.data.records;
            });
        },
        /* 模糊搜索类别选择*/
        // getItemValueData() {
        //     Api.getItemValue({
        //         comid: this.comid
        //     }).then(res => {
        //         this.dataList = res.data;
        //     });
        // },
        /* 表格分页方法 */
        handleChangePage(type, page) {
            this.loading = true;
            if (type == 'page') {
                this.search.pageindex = page;
                this.getTablesListData();
            } else {
                this.search.pagesize = page;
                this.getTablesListData();
            }
        },

        /* 表格查询 */
        handleSearch() {
            this.loading = true;
            this.getTablesListData();
        },
        /* 关闭对话框 */
        handleClose(type) {
            this.listType = type;
            if (this.listType == 'userClose') {
                this.isModal = false;
            } else {
                this.isModal = false;
            }
        },
        /* 复选框选中 */
        handleAllSelect(list) {
            let arr = [];
            for (let item in list) {
                arr.push(list[item].ID);
                arr.join(',');
            }
            arr = arr.join(',');
            this.allSelectArr = arr;
        },
        /* 对话框提交 */
        handleSubmit() {
            const { formItem, itemId } = this;
            this.$refs.formItem.validate(valid => {
                if (valid) {
                    let data = {
                        ID: itemId,
                        PageName: formItem.SpecialArea,
                        ModelIDS: formItem.OrderID.join(',')
                    };
                    Api.postSubmitForm(data).then(res => {
                        if (res.state == 'success') {
                            this.$Message.success('操作成功');
                            this.loading = true;
                            this.handleClose();
                            this.getTablesListData();
                        } else {
                            this.$Message.error(res.message);
                        }
                    });
                }
            });
        },
        /* 对话框操作点击 */
        handleBtnClick(item, type) {
            this.formItem.OrderID = [];
            this.formItem.Order = [];
            this.formItem.SpecialArea = '';
            this.formItem.currentPersonnel = [];
            this.initFormValidate();
            this.isModal = true;
            this.initFormValidate();
            this.itemId = 0;
            this.isModal = true;
            if (type == 'edit') {
                this.type = 'edit';
                this.itemId = item.ID;
                Api.getPlateList().then(res => {
                    this.personnelList = res.data.rows;
                });
                this.ModalTitle = '修改专区';
                // 获取一条的id;
                Api.getItemInfo({
                    id: item.ID
                }).then(res => {
                    // 赋值给表单
                    this.isModal = true;
                    this.formItem.SpecialArea = res.data.PageName;
                    let bbb = [];
                    for (let i = 0, len = res.data.ModelIDS.split(',').length; i < len; i++) {
                        for (let j = 0, len2 = this.personnelList.length; j < len2; j++) {
                            if (res.data.ModelIDS.split(',')[i] == this.personnelList[j].ID) {
                                bbb.push(`${res.data.ModelIDS.split(',')[i]}` + `/${this.personnelList[j].ModelName}`);
                            }
                        }
                    }
                    this.formItem.currentPersonnel = bbb;
                    this.getplateData();
                });
            }
            Api.getPlateList().then(res => {
                this.personnelList = res.data.rows;
            });
            //this.formItem = this.initFormValidate();
        },

        /* 表单数据 */
        initFormValidate() {
            return {
                currentPersonnel: [],
                Order: [],
                OrderID: [],
                SpecialArea: ''
            };
        },
        /* 表单校验 */
        initRuleValidate() {
            return {
                SpecialArea: [
                    {
                        required: true,
                        message: '请输入专区名称',
                        trigger: 'blur'
                    }
                ],
                currentPersonnel: [{ required: true, type: 'array', min: 1, message: '请选择板块', trigger: 'change' }]
            };
        }
    }
};
</script>

<style lang="less" scoped>
.form-item-width {
    width: 300px;
}
.btn-wrap {
    margin: 0 15px;
}
.dle-btn {
    margin: 0 10px;
}
.search-con {
    padding: 10px 0;
    .search {
        &-col {
            display: inline-block;
            width: 200px;
        }
        &-input {
            display: inline-block;
            width: 200px;
            margin-left: 2px;
        }
        &-btn {
            margin-left: 2px;
        }
    }
}
</style>



